package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.common.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.pojo.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserService {

    @Autowired
    private RSAService2 rsaService2;


    @DubboReference(version = "1.0.0")
    private UserApi userApi;
    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public Long checkToken(String token) {
        Map<String, Object> map = JwtUtils.checkToken(token, this.rsaService2.getPublicKeyStr());
        if (CollUtil.isEmpty(map)) {
            return null;
        }
        return Convert.toLong(map.get("userId"));
    }


    public Boolean updatePhone(Long userId, String newPhone) {
        //先查询新手机号是否已经注册，如果已经注册，就不能修改
        User user =  this.userApi.queryByMobile(newPhone);
        if(ObjectUtil.isNotEmpty(user)){
            //新手机号已经被注册
            return false;
        }
        //修改手机号
        user=this.userApi.queryById(userId);
        user.setMobile(newPhone);
        return this.userApi.update(user);
    }

    public User queryUserByToken(String token) {

        Long userId = this.checkToken(token);

        User user = this.userApi.queryById(userId);

        return user;

    }
}
